<template>
  <div class="radio-detail" :class="{ 'visible': isVisible, 'exiting': isExiting }" @transitionend="handleTransitionEnd"
    v-if="radioDetailData.json_content">
    <div class="radio-detail-header" v-if="Object.keys(radioDetailData).length > 0">
      <van-icon name="arrow-left" class="close-details" @click="closeDetail" />
      <div class="details-header-title"></div>
      <i class="recommend-iconfont icon-favorites"></i>
    </div>

    <div class="radio-detail-scrollable" v-if="Object.keys(radioDetailData).length > 0">
      <div class="radio-detail-cover">
        <img :src="radioDetailData.json_content.cover" alt="">
        <div class="play-btn" :class="{ 'playing': detailAudioPlaying }" @click="handlePlayClick">
        </div>
      </div>

      <div class="radio-detail-content">

        <div class="radio-detail-title">{{ radioDetailData.json_content.title }}</div>
        <div class="simple_author">
          <div class="author">{{ radioDetailData.json_content.simple_author[0] }}</div>
          <div class="phase">{{ radioDetailData.json_content.simple_author[1] }}</div>
        </div>

        <div class="radio-detail-text" v-html="radioDetailData.json_content.content"></div>

        <div class="detail-text-editor">{{ radioDetailData.json_content.editor }}</div>

        <div class="one-radio">
          <div class="one-radio-cover" :style="{ backgroundImage: 'url(' + radioDetailData.json_content.cover + ')' }">
          </div>
          <div class="one-radio-info">
            <span>ONE收音机</span>
            <span>"讲述生活，与你常在"</span>
          </div>
        </div>

        <div class="radio-details-author">
          <span>作者</span>
          <div class="author-box">
            <div class="author-left">
              <div class="author-avatar"
                :style="{ backgroundImage: 'url(' + radioDetailData.json_content.author.authors[0].avatar + ')' }">
              </div>
              <div class="author-info">
                <div class="author-name">{{ radioDetailData.json_content.author.authors[0].name }}</div>
                <div class="author-summary">{{ radioDetailData.json_content.author.authors[0].brief }}</div>
              </div>
            </div>
            <div class="follow-btn">关注</div>
          </div>
        </div>

        <div class="comment-list" ref="commentList">
          <span>评论列表</span>
          <div class="comment-list-item" v-for="(item, index) in radioCommentData" :key="`comment-${item.id}-${index}`">
            <div class="comment-list-item-head">
              <div class="comment-list-item-user">
                <div class="comment-user-avatar" :style="{ backgroundImage: 'url(' + item.user.web_url + ')' }"></div>
                <div class="comment-user-name">{{ item.user.user_name }}</div>
              </div>
              <div class="comment-input-date">{{ item.input_date.replace(/-/g, '.').split(':').slice(0, 2).join(':')
                }}
              </div>
            </div>
            <div class="quoted-comment" v-if="item.quote !== '' && item.touser !== null">{{ item.touser.user_name
              }}：{{
                item.quote }}</div>
            <div class="comment-content">{{ item.content }}</div>
            <div class="comment-function-icon">
              <i></i>
              <div class="praise">
                <i @click.stop="togglePraise(item)" :style="{
                  backgroundImage: item.isPraised
                    ? `url(${require('../assets/detail-icon/praise-active.svg')})`
                    : `url(${require('../assets/detail-icon/praise.svg')})`
                }"></i>
                <span class="praisenum">{{ item.praisenum }}</span>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>

    <div class="radio-details-bottom" v-if="Object.keys(radioDetailData).length > 0">
      <div class="write-comments" @click="handleWriteComment">
        写一个评论...
      </div>

      <div class="bottom-function-icon">
        <div class="like">
          <i class="one-icon" :class="radioDetailData.isLiked ? 'one-icon-liked' : 'one-icon-like'"
            @click="toggleLike(radioDetailData)"></i>
          <span>{{ radioDetailData.praisenum }}</span>
        </div>

        <div class="comment" @click="scrollToCommentList">
          <i></i>
          <span>{{ radioDetailData.commentnum }}</span>
        </div>

        <i class="one-icon one-icon-share"></i>
      </div>
    </div>

    <div v-if="Object.keys(radioDetailData).length == 0" class="loading">加载中...</div>
  </div>
</template>

<script>
import { getRadioDetail, getRadioComments } from '@/api/api';
import { mapState, mapActions } from 'vuex';
import { Icon } from 'vant';

export default {
  components: {
    [Icon.name]: Icon
  },
  name: 'RadioDetail',
  props: {
    radioId: {
      type: [String, Number],
      default: null
    },
    isVisible: {
      type: Boolean,
      default: false
    },
    currentDetailItem: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      radioDetailData: {}, // 当前电台详情数据
      isExiting: false, // 控制详情页退出动画
      radioCommentData: [], // 电台评论数据
      isLoading: false
    }
  },
  computed: {
    // 映射Vuex状态到组件
    ...mapState('audio', {
      currentAudio: state => state.currentAudio,
      isPlaying: state => state.isPlaying
    }),
    // 详情页播放状态（根据当前音频是否为详情页音频判断）
    detailAudioPlaying() {
      return this.isPlaying && this.currentAudio?.id === this.currentDetailItem?.id
    }
  },
  watch: {
    radioId: {
      handler(newId) {
        if (newId && this.isVisible) {
          this.fetchRadioDetail(newId);
        }
      },
      immediate: true
    },
    isVisible(newVal) {
      if (newVal && this.radioId) {
        this.fetchRadioDetail(this.radioId);
      } else if (!newVal) {
        this.isExiting = false;
      }
    }
  },
  methods: {
    // 映射Vuex actions到组件
    ...mapActions('audio', ['togglePlay', 'pauseAudio']),

    // 处理播放按钮点击
    handlePlayClick() {
      // 确保 currentDetailItem 存在且有 audio_url
      if (this.currentDetailItem && this.currentDetailItem.audio_url) {
        this.togglePlay(this.currentDetailItem);
      } else if (this.currentDetailItem && this.currentDetailItem.id) {
        // 如果有 id 但没有 audio_url，尝试从详情数据中获取
        console.warn('currentDetailItem 缺少 audio_url，无法播放音频');
      } else {
        console.warn('currentDetailItem 不存在，无法播放音频');
      }
    },

    // 获取电台详情数据
    fetchRadioDetail(radioId) {
      this.isLoading = true;

      getRadioDetail(radioId)
        .then(res => {
          this.radioDetailData = res.data;
        })
        .catch(err => console.error('获取详情失败:', err))
        .finally(() => this.isLoading = false);

      getRadioComments(radioId)
        .then(res => {
          this.radioCommentData = res.data.data;
        })
        .catch(err => console.error('获取评论失败:', err));
    },

    // 关闭详情页方法
    closeDetail() {
      this.isExiting = true;
    },
    handleWriteComment() {
      // 检查登录状态
      const isLoggedIn = localStorage.getItem('isLoggedIn');
      if (isLoggedIn !== 'true') {
        // 未登录，先显示提示，然后显示登录组件
        this.$toast({
          message: '请先登录账号',
          position: 'top',
        });
        setTimeout(() => {
          this.$root.$emit('showLoginRegister', this.$route.path);
        }, 300);
        return;
      }
      this.$toast({
        message: '功能暂未开放，尽请期待',
        position: 'bottom'
      });
    },

    // 过渡动画结束处理
    handleTransitionEnd() {
      if (this.isExiting) {
        // 重置状态
        this.isExiting = false;
        this.radioDetailData = {};
        this.radioCommentData = [];
        this.$emit('close');
      }
    },

    // 切换点赞状态
    toggleLike(item) {
      // 检查登录状态
      const isLoggedIn = localStorage.getItem('isLoggedIn');
      if (isLoggedIn !== 'true') {
        // 未登录，先显示提示，然后显示登录组件
        this.$toast({
          message: '请先登录账号',
          position: 'top',
        });
        setTimeout(() => {
          this.$root.$emit('showLoginRegister', this.$route.path);
        }, 300);
        return;
      }

      if (item.isLiked) {
        item.like_count--;
      } else {
        item.like_count++;
      }
      item.isLiked = !item.isLiked;
    },

    // 切换评论点赞状态，更新点赞数量
    togglePraise(item) {
      if (item.isPraised) {
        item.praisenum--;
      } else {
        item.praisenum++;
      }
      item.isPraised = !item.isPraised;
    },

    // 跳转到评论列表
    scrollToCommentList() {
      const commentListEl = this.$refs.commentList;
      if (commentListEl) {
        commentListEl.scrollIntoView({
          behavior: 'smooth',
          block: 'start'
        });
      }
    }
  }
}
</script>

<style scoped lang="less">
@import url('../assets/recommend-icon/iconfont.css');

.play-btn {
  display: block;
  position: absolute;
  z-index: 5;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  background-image: url(../assets/play.svg);

  &.playing {
    background-image: url(../assets/pause.svg);
  }
}

.radio-detail {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 12;
  background-color: #fff;
  transition: transform 0.3s ease;
  transform: translateY(100%);
  opacity: 0;

  &.visible {
    transform: translateY(0);
    opacity: 1;
  }

  &.exiting {
    transform: translateX(100%);
  }

  .radio-detail-header {
    width: 100%;
    height: 6vh;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 3vw;
    box-sizing: border-box;
    background-color: transparent;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 10;

    .close-details {
      font-size: 14px;
      color: #eee;
      cursor: pointer;
    }
  }

  .radio-detail-scrollable {
    position: fixed;
    top: 6vh;
    bottom: 6vh;
    left: 0;
    right: 0;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  .radio-detail-cover {
    width: 100%;
    position: relative;

    img {
      width: 100%;
    }

    .play-btn {
      width: 30px;
      height: 30px;
      bottom: 4vh;
      left: 50%;
      transform: translateX(-50%);
    }
  }

  .radio-detail-content {
    width: 100%;
    background-color: #fff;
    padding: 0 3vw;
    box-sizing: border-box;

    .radio-detail-title {
      font-size: 18px;
      font-weight: 600;
      padding: 4vh 0;
      box-sizing: border-box;
      letter-spacing: 1px;
    }

    .simple_author {
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      font-size: 9px;
      font-weight: 350;
    }

    .radio-detail-text {
      margin-top: 4vh;
      box-sizing: border-box;

      ::v-deep p {
        line-height: 2;
        margin-bottom: 3vh;
        font-size: 12px;
        font-weight: 350;
      }
    }

    .detail-text-editor {
      font-size: 9px;
      font-weight: 300;
      padding-bottom: 4vh;
    }

    .one-radio {
      width: 100%;
      height: 10vh;
      background-color: #fbfbfb;
      padding: 2vh 0;
      box-sizing: border-box;
      border: none;
      display: flex;
      align-items: center;
      gap: 2vw;

      .one-radio-cover {
        height: 100%;
        aspect-ratio: 1/1;
        background-size: 300%;
        background-position: center;
        background-repeat: no-repeat;
      }

      .one-radio-info {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        gap: 1vh;
        font-size: 10px;
        font-weight: 350;

        span:nth-child(2) {
          font-size: 8px;
          font-weight: 300;
        }
      }
    }

    .radio-details-author {
      width: 100%;
      margin: 3vh 0;
      display: flex;
      flex-direction: column;
      gap: 2vh;

      span {
        font-size: 10px;
        font-weight: 300;
        padding: 1vh 0 1.8vh;
        position: relative;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          width: 10vw;
          height: 3px;
          background-color: #000;
        }
      }

      .author-box {
        width: 100%;
        height: 5vh;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .author-left {
          height: 100%;
          display: flex;
          align-items: center;
          gap: 2vw;

          .author-avatar {
            height: 90%;
            aspect-ratio: 1/1;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            border-radius: 50%;
          }

          .author-info {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            height: 100%;
            padding: 3px 0;
            box-sizing: border-box;

            .author-name {
              font-size: 10px;
              font-weight: 300;
            }

            .author-summary {
              font-size: 8px;
              font-weight: 300;
              color: #8c8c8c;
            }
          }
        }

        .follow-btn {
          font-size: 10px;
          border: 1px solid #aaa;
          color: #aaa;
          padding: 1.5vw 2vw;
          border-radius: 2px;
          box-sizing: border-box;
        }
      }

    }

    .comment-list {
      width: 100%;
      margin: 3vh 0;
      display: flex;
      flex-direction: column;
      gap: 2vh;

      >span {
        font-size: 10px;
        font-weight: 300;
        padding: 1vh 0 1.8vh;
        position: relative;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          width: 10vw;
          height: 3px;
          background-color: #000;
        }
      }

      .comment-list-item {
        width: 100%;
        min-height: 10vh;
        border-bottom: 1px solid #ddddddd7;

        .comment-list-item-head {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 20%;
          width: 100%;
          margin-bottom: 2vh;

          .comment-list-item-user {
            display: flex;
            align-items: center;
            gap: 1vw;
            height: 100%;

            .comment-user-avatar {
              height: 2vh;
              aspect-ratio: 1/1;
              border-radius: 50%;
              background-size: cover;
              background-position: center;
              background-repeat: no-repeat;
            }

            .comment-user-name {
              font-size: 10px;
              font-weight: 300;
              color: #aaa;
            }
          }

          .comment-input-date {
            font-size: 8px;
            font-weight: 300;
          }
        }

        .quoted-comment,
        .comment-content {
          width: 95%;
          margin-left: 5%;
          font-size: 10px;
          font-weight: 350;
          margin-bottom: 2vh;
          line-height: 1.8;
        }

        .quoted-comment {
          border: 1px solid #ddd;
          padding: 1.2vh 2vw;
          box-sizing: border-box;
          border-radius: 4px;
        }

        .comment-function-icon {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          gap: 3vw;
          padding-right: 5vw;
          margin-bottom: 1vh;

          i {
            display: inline-block;
            width: 12px;
            height: 12px;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
          }

          >i {
            background-image: url(../assets/detail-icon/comment.svg);
          }

          .praise {
            display: flex;
            align-items: center;
            gap: 1vw;
            font-size: 8px;
            color: #aaa;
          }
        }

      }
    }
  }

  .radio-details-bottom {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 6vh;
    z-index: 1;
    padding: 0 3vw;
    box-sizing: border-box;
    background-color: #f7f7f7;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .write-comments {
      height: 60%;
      font-size: 10px;
      color: #cdcdcd;
      background-color: #fff;
      padding: 0 2vw;
      padding-right: 8vw;
      box-sizing: border-box;
      border: 1px solid #a8a8a8a4;
      border-radius: 4px;
      display: flex;
      align-items: center;
    }

    .bottom-function-icon {
      display: flex;
      align-items: center;
      gap: 4vw;

      .like span,
      .comment span {
        font-size: 8px;
        color: #cdcdcd;
      }

      .like,
      .comment {
        display: flex;
        align-items: flex-start;
      }

      .like {
        gap: 3px;
      }

      .comment>i {
        display: block;
        width: 12px;
        height: 12px;
        background-image: url(../assets/detail-icon/comment.svg);
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
      }

      .one-icon {
        font-size: 12px;
        color: #cdcdcd;
      }
    }
  }
}

.loading {
  width: 100%;
  text-align: center;
  padding: 20px;
  font-size: 14px;
  color: #999;
}
</style>